interface TouchEvent {
  touches: { clientX: number; clientY: number }[]
  changedTouches: { clientX: number; clientY: number }[]
}
const app = getApp()

let touchStartX: number = 0
let touchStartY: number = 0
let touchEndX: number = 0
let touchEndY: number = 0

Page({
  data: {
    cellArr: [] as number[][]
  },
  onLoad: function () {
    this.startGame()
  },
  startGame() {
    this.setData({
      cellArr: [
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]
      ]
    }
    )
    this.fillOneEmptyCell()
    this.fillOneEmptyCell()
  },
  fillOneEmptyCell() {
    const emptyCells = this.findEmptyCells()
    const index = this.getRandomPos(emptyCells.length)
    const [row, col] = emptyCells[index]
    this.data.cellArr[row][col] = this.getRandomValue()
    this.setData({ cellArr: this.data.cellArr })
  },
  getRandomValue(): number {
    if (Math.random() < 0.9) {
      return 2
    } else {
      return 4
    }
  },
  getRandomPos(length: number) {
    return Math.floor(Math.random() * length)
  },
  findEmptyCells(): [number, number][] {
    const result: [number, number][] = []
    for (let i = 0; i < 4; i++) {
      for (let j = 0; j < 4; j++) {
        if (this.data.cellArr[i][j] === 0) {
          result.push([i, j])
        }
      }
    }
    return result
  },
  touchStart(event: TouchEvent) {
    const touch = event.touches[0]
    touchStartX = touch.clientX
    touchStartY = touch.clientY
    touchEndX = touch.clientX
    touchEndY = touch.clientY
  },
  touchMove(event: TouchEvent) {
    const touch = event.touches[0]
    touchEndX = touch.clientX
    touchEndY = touch.clientY
  },
  touchEnd() {
    const disX = touchEndX - touchStartX
    const absDisx = Math.abs(disX)
    const disY = touchEndY - touchStartY
    const absDisY = Math.abs(disY)

    if (absDisx > 10 || absDisY > 10) {
      if (absDisx > absDisY) {
        if (disX > 0) {
          this.move('right')
        } else {
          this.move('left')
        }
      } else {
        if (disY > 0) {
          this.move('down')
        } else {
          this.move('up')
        }
      }
    }
  },
  move(direction: string) {
    console.log(direction);
  }
})
